package com.tnovoselec.android.feed.handler.async;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import android.content.Context;
import android.util.Log;

import com.nth.android.Util;
import com.tnovoselec.android.favorites.entity.NewsFavoritesDto;
import com.tnovoselec.android.feed.handler.NewsParser;
import com.tnovoselec.android.feed.handler.resultholders.NewsResultHolder;


public class DownloadNews implements Callable<Boolean> {

    private final String TAG = DownloadNews.class.getSimpleName();

    private String xmlUrl;
    private String parentChannelId;
    private Context context;
    private boolean fromCache;
    private String pathToSave;

    public DownloadNews(String xmlUrl, String parentChannelId, Context context, boolean fromCache, String pathToSave) {
	super();
	this.xmlUrl = xmlUrl;
	this.parentChannelId = parentChannelId;
	this.context = context;
	this.fromCache = fromCache;
	this.pathToSave = pathToSave;
    }

    @Override
    public synchronized Boolean call() throws Exception {
	HttpURLConnection connection = null;
	InputStream is = null;

	try {

	    // TODO ubaciti u Util framework
	    if (!fromCache) {
		URL imageUrl = new URL(xmlUrl.trim());
		connection = (HttpURLConnection) imageUrl.openConnection();
		connection.setConnectTimeout(Util.HTTP_CONNECT_TIMEOUT);
		connection.setReadTimeout(Util.HTTP_READ_TIMEOUT);
		connection.setDoInput(true);
		connection.connect();
		is = connection.getInputStream();
		// Util.fileCreate(xmlUrl, is, context);
		Util.fileCreate(xmlUrl, is, pathToSave);
	    }

	    // if (Util.fileExistsHex(xmlUrl, context)) {
	    // is = Util.readFile(xmlUrl, context);
	    // } else {
	    // return Boolean.FALSE;
	    // }
	    if (Util.fileExistsHex(xmlUrl, pathToSave)) {
		is = Util.readFile(xmlUrl, pathToSave);
	    } else {
		return Boolean.FALSE;
	    }

	    NewsParser parser = new NewsParser(parentChannelId);
	    SAXParserFactory factory = SAXParserFactory.newInstance();
	    SAXParser sp = factory.newSAXParser();
	    sp.parse(is, parser);
	    List<NewsFavoritesDto> items = new ArrayList<NewsFavoritesDto>();
	    items = parser.getNews();
	    NewsResultHolder.init(parentChannelId, items);
	} catch (Exception ex) {
	    Log.e(TAG, ex.getMessage(), ex);
	    return Boolean.FALSE;
	}
	return Boolean.TRUE;
    }

}
